$(function() {
	// 文本编辑器
	if ($("#editor").length > 0)
		var ueditor = UE.getEditor('editor', {
			initialFrameWidth : 745
		});
	// tag输入栏
	var tagsInput = $('#txt_tags');

	// init controls
	initControls();
	function initControls() {
		// 定义推荐

		// 生成tag
		if (tagsInput != null && tagsInput != 'undefined'
				&& tagsInput.length > 0) {
			var tagEngine = new Bloodhound({
				datumTokenizer : Bloodhound.tokenizers.obj.whitespace('name'),
				queryTokenizer : Bloodhound.tokenizers.whitespace,
				remote : '/faxsun-info/admin/tags/tagQuery?q=%QUERY',
				limit : 30
			});
			tagEngine.initialize();
			tagsInput.tagsinput({
				tagClass : function(item) {
					if (item.name == '热门')
						return 'label label-danger label-important';
					switch (item.type) {
					case 'PRODUCT':
						return 'label label-primary';
					case 'CATEGORY':
						return 'label label-success';
						// case 'Africa' : return 'label label-default';
					case 'NORMAL':
						return 'label label-warning';
					}
				},
				itemValue : 'id',
				itemText : 'name',
				typeaheadjs : {
					name : 'tagEngine',
					displayKey : 'name',
					source : tagEngine.ttAdapter()
				}
			});

		}
		$("#banner_settings").hide();
		/*
		 * for(tagIndex in tagsArray){ elt.tagsinput('add',
		 * ''tagsArray[tagIndex]); }
		 */

		// 根据隐藏字段设置内容
		loadHiddenFields();

		if ($("#coverImage").length > 0) {
			var coverImage = $('#coverImageUrl').val();

			if (coverImage == null || coverImage == '') {
				// 初始化封面图片
				$("#coverImage")
						.fileinput(
								{
									uploadUrl : "/faxsun-info/ueditor/dispatch?action=uploadimage", // server
									// upload
									// action
									uploadAsync : true,
									minFileCount : 1,
									maxFileCount : 1
								});
			} else {
				$("#coverImage")
						.fileinput(
								{
									uploadUrl : "/faxsun-info/ueditor/dispatch?action=uploadimage", // server
									// upload
									// action
									uploadAsync : true,
									minFileCount : 1,
									maxFileCount : 1,
									initialPreview : [
											"<img src='"
													+ coverImage
													+ "' class='file-preview-image' alt='cover' title='cover'>", ],
								});
			}
		}

	}// end of init controls

	function deletePost(element) {
		// send get request
		var url = $(element).attr('href');
		$.get(url).done(function(data) {
			// 删除成功，加载数据
			console.log(data.code);
			if (data.code == 0) {
				$('#postTable').bootstrapTable('refresh');
				alert("删除成功");
			} else {
				alert("删除失败!" + data.message);
			}
		});
		return false;
	}

	// init events
	$("#notBanner").click(function(e) {
		$("#banner_settings").hide();
	});

	$("#isBanner").click(function(e) {
		$("#banner_settings").show();
	});

	$('#coverImage').on('fileuploaded',
			function(event, data, previewId, index, jqXHR) {

				if (data.response.state = 'SUCCESS') {
					$('#coverImageUrl').val(data.response.url);
				}
			});

	// tags events
	$('#txt_tags').on('itemAdded', function(event) {
		// event.item: contains the item
		var tags = $("input[name='tags']").val().split(",");
		var existed = false;
		for (tag in tags) {
			if (tags[tag] == event.item.name) {
				existed = true;
				break;
			}
		}
		// 隐藏字段中添加tag name
		if (!existed) {
			if (tags == '')
				$("input[name='tags']").val(event.item.name);
			else
				$("input[name='tags']").val(tags + "," + event.item.name);
		}

		resetProductTag();
	});

	$('#txt_tags').on('itemRemoved', function(event) {
		// event.item: contains the item
		var tags = $("input[name='tags']").val().split(",");

		var index = -1;
		for (tag in tags) {
			index++;
			if (tags[tag] == event.item.name) {
				break;
			}
		}
		if (index >= 0) {
			tags.splice(index, 1);
		}
		// 移除隐藏字段中的tag name
		$("input[name='tags']").val(tags.toString());

		resetProductTag();
	});

	$('#postTable').on('load-success.bs.table', function(e, data) {
		// 删除确认
		$(".confirm").confirm({
			text : "确认是否删除文章?",
			title : "确认",
			confirm : function(button) {
				deletePost(button);
			},
			cancel : function(button) {
				// nothing to do
			},
			confirmButton : "确定",
			cancelButton : "取消",
			post : true,
			confirmButtonClass : "btn-danger",
			cancelButtonClass : "btn-default",
			dialogClass : "modal-dialog modal-lg" // Bootstrap classes for
		// large modal
		});
	});

	// 对于已有内容，从隐藏字段加载标签和编辑器内容
	function loadHiddenFields() {
		if ($('#tags_temp').length > 0) {
			var tags = $.parseJSON($('#tags_temp').val());
			if (tags !== null && tags !== '') {
				$.each(tags, function(i, tag) {
					tagsInput.tagsinput('add', tag);
				});
			}
		}
		if (ueditor != null && ueditor != 'undefined') {
			ueditor.ready(function() {
				var content = $('#content_temp').val();
				ueditor.setContent(content);
			});
		}

		if ($('#default_product').length > 0) {
			var defaultProductTag = $('#default_product').val();
			$("#productTag.id").val(defaultProductTag);
			// $("#productTag.id").find("option[val=" + defaultProductTag + "]")
			// .attr("selected", true);
		}
	}

	// 标签改变，检查是否需要重设产品tag，取标签栏的第一个产品tag做为默认产品tag
	function resetProductTag() {
		var tagItems = $('#txt_tags').tagsinput('items');
		$("select[id='productTag.id']").val(0);
		for (i in tagItems) {
			tagItem = tagItems[i];
			if (tagItem.type = 'PRODUCT') {
				if ($('#default_product').length > 0) {
					$('#default_product').val(tagItem.id);
					$("select[id='productTag.id']").val(tagItem.id);
				}
				break;
			}
		}
	}
});